package com.all.shiro.realm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author LY
 * @create 2024/4/3 17:27
 * @Description 自定义 Shiro Realm 授权
 */
@Component
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("授权 ===>>>");
        Subject subject = SecurityUtils.getSubject();
        log.info("授权用户：{}", subject.getPrincipal());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        // 授予权限
        Set<String> permissions = new HashSet<>();
        permissions.add("/user/add");
        permissions.add("/user/del");
        permissions.add("/user/edit");

        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("认证 ===>>>");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 获取登录用户名
        String username = token.getUsername();
        // 获取登录密码
        String password = String.valueOf(token.getPassword());
        // 校验登录
        if (username.equals("admin")){
            // 登录成功
            return new SimpleAuthenticationInfo(username, password, username);
        }
        return null;
    }
}
